/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ppsa.Servlet;

import com.ppsa.common.Util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONObject;

/**
 *
 * @author JONATAN
 */
//@WebServlet(name = "ServletListado", urlPatterns = {"/upload"})
@MultipartConfig
public class ServletListado extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, FileUploadException {
        //response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        //response.setContentType("text/html");
        System.out.println("****************************************************");
        JSONObject objL_json = new JSONObject();
        int namePDF = 0 ;
       

        

        boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
        if (!isMultipartContent) {
            out.println("You are not trying to upload");
            return;
        }
        //out.println("bbbbYou are trying to upload");
        //out.println("aaaaaa");
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> fields = upload.parseRequest(request);
            
            Iterator<FileItem> it = fields.iterator();
            if (!it.hasNext()) {
                out.println("No fields found");
                return;
            }
            
            while (it.hasNext()) {
                
                FileItem fileItem = it.next();
                boolean isFormField = fileItem.isFormField();
                String extension = "";
                if (!isFormField) {
                        String fileName = fileItem.getName();
                        
                        int dotPos = fileItem.getName().lastIndexOf(".");
			extension = fileItem.getName().substring(dotPos);
                        System.out.println( " extension  -->" +  extension );
                        String root =  getServletContext().getRealPath("/");//getServletContext().getContextPath();
                        
                        File path = new File( root );
                        if (!path.exists()) {
                            boolean status = path.mkdirs();
                        }
                        //System.out.println("-+---> " + status);
                        namePDF = new Double(Math.random() * 10000000).intValue();
                        File uploadedFile = new File(/*path +*/ "D://pdf/"  + File.separator + fileName );
                        
                        File uploadedFile2 = new File(/*path +*/ "D://pdf/"  + File.separator +  namePDF  + extension );
                        
                        uploadedFile.renameTo(uploadedFile2);
                        /*
                         File oldfile =new File("oldfile.txt");
                            File newfile =new File("newfile.txt");
 
		if(oldfile.renameTo(newfile)){
			System.out.println("Rename succesful");
		}else{
			System.out.println("Rename failed");
		}
                         */
                        fileItem.write(uploadedFile2);
                        
                       
               }
               out.println("pcr = "+namePDF);
                
               //Util.returnJSONWriter(response, "{nombre:acc}");
                /*if (isFormField) {
                    out.println("<td>regular form field</td><td>FIELD NAME: " + fileItem.getFieldName()
                            + "<br/>STRING: " + fileItem.getString());
                    out.println("</td>");
                } else {
                    out.println("<td>file form field</td><td>FIELD NAME: " + fileItem.getFieldName()
                            + "<br/>STRING: " + fileItem.getString()
                            + "<br/>NAME: " + fileItem.getName()
                            + "<br/>CONTENT TYPE: " + fileItem.getContentType()
                            + "<br/>SIZE (BYTES): " + fileItem.getSize()
                            + "<br/>TO STRING: " + fileItem.toString());
                    out.println("</td>");
                }*/
                
            }
            
        } catch (Exception ex) {
            Logger.getLogger(ServletListado.class.getName()).log(Level.SEVERE, null, ex);
        } 
    }

    private String getFileName(final Part part) {
        final String partHeader = part.getHeader("content-disposition");
        System.out.println("Part Header = {0}" + partHeader);
        for (String content : part.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(
                        content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(ServletListado.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(ServletListado.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
